package a02_链表;

/**
 * <p>
 * a07_环形链表2
 * </p>
 *
 * @author flyduck
 * @since 2024-06-20
 */
public class a08_环形链表2复习2 {

    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        ListNode listNode = new ListNode(2);
        head.next = listNode;
        head.next.next = new ListNode(0);
        head.next.next.next = new ListNode(-4);
        head.next.next.next.next = listNode;
        ListNode listNode1 = detectCycle(head);
        System.out.println(listNode1.val);
    }

    public static ListNode detectCycle(ListNode head) {
        ListNode slowNode = head;
        ListNode fastNode = head;
        while (fastNode != null && fastNode.next != null) {
            slowNode = slowNode.next;
            fastNode = fastNode.next.next;
            if(slowNode == fastNode){
                ListNode node1 = head;
                ListNode node2 = slowNode;
                while (node1 != node2) {
                    node1 = node1.next;
                    node2 = node2.next;
                }
                return node1;
            }
        }
        return null;

    }
}
